<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { Pod, LabelSelector } from "@/views/domain/kubeHud/api/k8s/types";
import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import { objectToList, timeTrans } from "@/views/domain/kubeHud/utils";
import RouterLinkBtn from "@/views/widgets/RouterLinkBtn/index.vue";
import PodStatusIcon from "./PodStatusIcon.vue";
import KSpace from "../../components/KSpace.vue";
import PodContainerTable from "./PodContainerTable.vue";
import { KubeHudRouterPath } from "@/views/domain/kubeHud/router";

type Prop = {
  namespace?: string;
  nodeName?: string;
  selector?: LabelSelector;
  pods?: Pod[];
};

const { podRepo } = useK8SApi();
const props = defineProps<Prop>();
const emit = defineEmits(["update:pods"]);

const podList = ref<Pod[]>();
const total = ref(0);
const nextToken = ref();
const loading = ref(false);
const expands = ref([]);

const labelSelector = computed(() => {
  const srcs = [
    props.nodeName ? `spec.nodeName=${props.nodeName}` : "",
    ...objectToList(props.selector).map(v => `${v.key}=${v.value}`)
  ];
  return srcs.filter(v => v !== "").join(",");
});

const loadPodList = async () => {
  loading.value = true;
  const { ok, data } = await podRepo.getPodList({
    namespace: props.namespace,
    labelSelector: labelSelector.value,
    continue: nextToken.value
  });

  if (ok) {
    podList.value = data.items;
    nextToken.value = data.metadata?.continue;
    total.value = data.metadata.remainingItemCount ?? data.items?.length;
    emit("update:pods", podList.value);
  }
  loading.value = false;
};

const onExpanded = (row: any) => {
  if (expands.value.includes(row.metadata.name)) {
    expands.value = [];
  } else {
    expands.value = row ? [row.metadata.name] : [];
  }
};

onMounted(() => {
  if (props.pods) {
    podList.value = props.pods;
  } else {
    loadPodList();
  }
});

watch(
  () => props.pods,
  pods => {
    pods && (podList.value = pods);
  }
);

watch(
  () => props.namespace,
  ns => {
    ns && loadPodList();
  }
);
</script>

<template>
  <div v-loading="loading" class="w-full pod-table-wrapper">
    <div />
    <el-table
      :data="podList"
      table-layout="fixed"
      row-key="metadata.name"
      :expand-row-keys="expands"
      @expand-change="onExpanded"
    >
      <el-table-column type="expand">
        <template #default="{ row }">
          <div class="w-full pl-10 pr-1">
            <PodContainerTable :pod="row" />
          </div>
        </template>
      </el-table-column>
      <!-- Status Icon -->
      <el-table-column width="64px">
        <template #default="{ row }">
          <PodStatusIcon :pod="row" />
        </template>
      </el-table-column>
      <!-- Name -->
      <el-table-column>
        <template #default="{ row }">
          <KSpace direction="column">
            <RouterLinkBtn
              :to="KubeHudRouterPath.PodDetails"
              :query="{
                name: row.metadata.name,
                namespace: row.metadata.namespace
              }"
              :label="row.metadata.name"
            />
            <span
              >创建于:
              {{
                timeTrans(row.metadata.creationTimestamp, "YYYY-MM-DD HH:mm:ss")
              }}</span
            >
          </KSpace>
        </template>
      </el-table-column>
      <!-- Node -->
      <el-table-column>
        <template #default="{ row }">
          <KSpace direction="column">
            <span>
              {{ row.spec?.nodeName }}( {{ row.status?.hostIP || "-" }} )
            </span>
            <span>节点</span>
          </KSpace>
        </template>
      </el-table-column>

      <!-- PodIP -->
      <el-table-column>
        <template #default="{ row }">
          <KSpace direction="column">
            <span>{{ row.status?.podIP || "-" }}</span>
            <span>容器组IP</span>
          </KSpace>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<style lang="scss" scoped>
.pod-table-wrapper {
  :deep(.el-table) {
    --el-border-color-lighter: none;
    --el-table-expanded-cell-bg-color: var(--el-bg-color-page);
    --el-table-current-row-bg-color: var(--el-bg-color-page);
    --el-table-row-hover-bg-color: var(--el-bg-color-page);
  }
  :deep(thead) {
    display: none;
  }
}
.container-badge {
  display: flex;
  position: relative;

  .badge {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 10px;
    height: 10px;
    border-radius: 50%;
  }

  .ready {
    background-color: var(--el-color-success);
  }

  .not-ready {
    background-color: var(--el-color-danger);
    animation: blink-and-change-color 2s infinite ease-in-out;
  }

  @keyframes blink-and-change-color {
    /* 动画开始时的状态，文字完全显示，颜色为红色 */
    0% {
      opacity: 1;
      background-color: var(--el-color-danger);
    }
    /* 动画进行到50%时的状态，文字完全隐藏，颜色为蓝色 */
    50% {
      opacity: 0.5;
      background-color: var(--el-color-danger);
    }
    /* 动画结束时的状态，文字完全显示，颜色为红色 */
    100% {
      opacity: 1;
      background-color: var(--el-color-danger);
    }
  }
}
</style>
